package com.tongqu.server;

import com.tongqu.config.NettyConfig;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

@Component
public class ServerOperation {

    @Autowired
    @Qualifier(value = "bossGroup")
    private NioEventLoopGroup boss;

    @Autowired
    @Qualifier(value = "workGroup")
    private NioEventLoopGroup work;

    @Autowired
    private ServerBootstrap serverBootstrap;
    @Autowired
    NettyConfig nettyConfig;


    public void start() {

        try {
            System.out.println("服务器开启在端口" + nettyConfig.getPort());
            ChannelFuture channelFuture = serverBootstrap.bind(nettyConfig.getPort()).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }

    }


    @PreDestroy
    public void shutDown() {
        System.out.println("服务器关闭");
        boss.shutdownGracefully();
        work.shutdownGracefully();
    }
}
